import datetime
import json
import logging
import time

from django.core import serializers
from django.core.paginator import Paginator, EmptyPage
from django.core.serializers import serialize
from django.http import JsonResponse
from django.views import View

from celery_tasks.image.tasks import send_image_code
from house.models import Area, House, HouseImage
from ihome.utils.views import LoginRequiredMixin
from order.models import Order
from qiniuyun import qiniu_storage
from users.models import User

from django.shortcuts import render

# Create your views here.

from django import http
from django.core.cache import cache
from django.views import View

# 地区信息 || 缓存
from house.models import Area


class GetAreasView(View):

    def get(self, request):

        data = cache.get('data')
        if not data:
            try:
                areas = Area.objects.all()
                data = []
                for area in areas:
                    data.append({'aid': area.id,
                                 'aname': area.name})

                cache.set('data', data, 3600)

            except Exception as e:
                return http.JsonResponse({'code': 400,
                                          'errmsg': '省份数据错误'})

        return http.JsonResponse({"errmsg": "获取成功",
                                  'errno': 0,
                                  'data': data})


# 发布房源
class AddandSearchHouses(View):
    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        user_id = request.user.id

        # 获取标题
        title = json_dict.get('title')
        # 获取价格
        price = json_dict.get('price')
        # 获取城区id
        area_id = json_dict.get('area_id')
        # 获取房屋地址
        address = json_dict.get('address')
        # 获取房间数目
        room_count = json_dict.get('room_count')
        # 获取房屋面积
        acreage = json_dict.get('acreage')
        # 获取房屋单元
        unit = json_dict.get('unit')
        # 获取房屋容纳的人数
        capacity = json_dict.get('capacity')
        # 获取房屋床铺的配置
        beds = json_dict.get('beds')
        # 获取房屋押金
        deposit = json_dict.get('deposit')
        # 最少入住天数
        min_days = json_dict.get('min_days')
        # 最大入住天数，0表示不限制
        max_days = json_dict.get('max_days')
        # 用户选择的设施信息id列表
        facility = json_dict.get('facility')

        # 必要参数
        if not all([title, price, address, area_id, room_count, acreage, unit, capacity, beds
                       , deposit, min_days, max_days, facility]):
            return http.HttpResponseForbidden('缺少必传参数')

        try:

            area = Area.objects.get(id=area_id)
        except Area.DoesNotExist:
            return http.HttpResponseForbidden('地区不合法')

        try:

            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return http.HttpResponseForbidden('无该用户')

        if int(min_days) <= 0:
            return http.HttpResponseForbidden('最少为1天')

        try:
            house = House.objects.create(user_id=user_id,
                                         area_id=area_id,
                                         title=title,
                                         price=price,
                                         address=address,
                                         room_count=room_count,
                                         acreage=acreage,
                                         unit=unit,
                                         capacity=capacity,
                                         beds=beds,
                                         deposit=deposit,
                                         min_days=min_days,
                                         max_days=max_days)
            house.facility.set(facility)
        except Exception as e:
            return http.JsonResponse({'errno': 404,
                                      'errmsg': 'error',
                                      'data': None})

        return http.JsonResponse({'errno': 0,
                                  'errmsg': "Ok",
                                  'data': {"house_id": house.id}})

    def get(self, request):
        # 区域id
        aid = request.GET.get('aid')
        # 开始日期
        sd = request.GET.get('sd')
        # sd = datetime.datetime.strptime(sd, '%Y-%m-%d')
        # 结束时间
        ed = request.GET.get('ed')
        # ed = datetime.datetime.strptime(ed, '%Y-%m-%d')
        # 排序方式
        sk = request.GET.get('sk')
        # 页数
        p = int(request.GET.get('p'))

        if not all([aid, sd, ed]):
            return http.HttpResponseForbidden('缺少必传参数')

        try:
            area = Area.objects.get(id=aid)
        except Area.DoesNotExist:
            return http.JsonResponse({'errmsg': '请求失败', 'errno': 404})

        # 排序方式 booking(订单量), price-inc(低到高), price-des(高到低)
        if sk == 'booking':
            order_by = 'order_count'
        elif sk == 'price-inc':
            order_by = 'price'
        elif sk == 'price-dec':
            order_by = '-price'
        else:
            order_by = 'create_time'

        if sd > ed:
            return http.HttpResponseForbidden('入住时间不合法')

        try:
            orders = Order.objects.all()
            search_house = House.objects.filter(area_id=aid).order_by(order_by)
        except House.DoesNotExist:
            return http.JsonResponse({'errmsg': '请求失败', 'errno': 404})

        # 分页
        paginator = Paginator(search_house, 3)

        try:
            page_house = paginator.page(p)
            total_page = paginator.num_pages
        # 如果page_num不正确，默认给用户404
        except EmptyPage:
            return http.HttpResponseNotFound('empty page')

        # 区域所有房屋
        search_list = []

        for search in search_house:
            search_list.append(search.id)

        # 空房
        free_house = []  # house_id

        for order in orders:
            begin_date = str(order.begin_date)
            # begin_date = datetime.datetime.strptime(begin_date, '%Y-%m-%d')
            end_date = str(order.end_date)
            # end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            free_house = search_list
            if order.house_id in search_list and not (ed > begin_date or sd > end_date):
                search_list.remove(order.house_id)
                free_house = search_list

        search_houses = []
        # 当前可用房源对象
        for now_search_house in free_house:
            search_houses.append(House.objects.get(id=now_search_house))

        # 房源列表
        houses = []

        for house in search_houses:
            house_dict = {}
            house_dict['address'] = house.address
            house_dict['area_name'] = house.area.name
            house_dict['ctime'] = house.create_time
            house_dict['house_id'] = house.id
            house_dict['img_url'] = house.index_image_url
            house_dict['order_count'] = house.order_count
            house_dict['title'] = house.title
            house_dict['price'] = house.price * 100
            house_dict['room_count'] = house.room_count
            house_dict['title'] = house.title
            house_dict['user_avatar'] = str(house.user.avatar)
            # 添加一行记录
            houses.append(house_dict)

        data = {
            'total_page': total_page,
            'houses': houses
        }

        return http.JsonResponse({"data": data, "errmsg": "请求成功", "errno": "0"})


# 上传图片
class Upload_image(View):

    def post(self, request, house_id):
        try:
            image = request.FILES.get('house_image')

            img_url = send_image_code(image)

            print(img_url)
            try:
                house = House.objects.get(id=house_id)
                house.index_image_url = img_url
                HouseImage.objects.create(house_id=house.id, url=img_url)
                house.save()
            except Exception:
                return JsonResponse({
                    'errno': 4101,
                    'errmsg': "头像上传失败"
                })
            data = {
                "url": img_url
            }
        except Exception as e:
            return http.JsonResponse({"errno": 404,
                                      "errmsg": "获取数据失败"})

        return http.JsonResponse({"data": data, "errno": "0", "errmsg": "上传成功"})


# 我的房屋列表
class UserHouseDetialView(LoginRequiredMixin, View):
    def get(self, requset):
        try:
            user_id = requset.user.id
            user_house = House.objects.filter(user_id=user_id)

            houselist = []

            for house in user_house:
                create_time = house.create_time
                house_time_change = create_time.strftime('%Y-%m-%d %H:%M')
                houselist.append({'address': house.address,
                                  'area_name': house.area.name,
                                  'ctime': house_time_change,
                                  'house_id': house.id,
                                  'img_url': house.index_image_url,
                                  'order_count': house.max_days,
                                  'price': house.price,
                                  'room_count': house.room_count,
                                  'title': house.title,
                                  'user_avatar': str(house.user.avatar),
                                  })

        except Exception as e:
            return http.JsonResponse({"errno": 404,
                                      "errmsg": "获取数据失败"})

        return http.JsonResponse({"errmsg": 'OK',
                                  "errno": 0,
                                  "data": {"houses": houselist}})


# 首页房源推荐
class IndexHouseView(LoginRequiredMixin, View):

    def get(self, request):
        # 默认显示５张图片
        houses_list = House.objects.all().order_by('-order_count')[0:4]
        house_show_list = []
        for house in houses_list:
            house_show_list.append({'house_id': house.id,
                                    'img_url': house.index_image_url,
                                    'title': house.title})

        return http.JsonResponse({'data': house_show_list, 'errmsg': 'OK', 'errno': 0})


# 房屋详情
class HouseDetialView(View):
    def get(self, request, house_id):
        try:
            house = House.objects.get(pk=house_id)
        except:
            return http.HttpResponseForbidden('房间ｉｄ有误')

        # 获取评论
        comment_list = []
        orders = Order.objects.filter(house_id=house_id)
        for order in orders:
            comments = {
                'comment': order.comment,
                'ctime': order.create_time,
                'user_name': '匿名用户'
            }
            comment_list.append(comments)

        # 获取设施信息
        facility_list = []
        facilities = house.facility.all()
        for facility in facilities:
            id = facility.pk
            facility_list.append(id)

        # 生成房屋信息
        house_info = {}
        house_info['acreage'] = house.acreage
        house_info['address'] = house.address
        house_info['beds'] = house.beds
        house_info['capacity'] = house.capacity
        house_info['comments'] = comment_list
        house_info['deposit'] = house.deposit
        house_info['facilities'] = facility_list
        house_info['hid'] = house.pk
        house_info['img_urls'] = [Image.url for Image in HouseImage.objects.filter(house_id=house_id)]
        house_info['min_days'] = house.min_days
        house_info['max_days'] = house.max_days
        house_info['price'] = house.price
        house_info['room_count'] = house.room_count
        house_info['title'] = house.title
        house_info['unit'] = house.unit
        house_info['user_avatar'] = str(house.user.avatar)
        house_info['user_id'] = house.user_id
        house_info['user_name'] = house.user.username

        # 当前登录用户的用户id，如果没有登录，则为 -1
        user = request.user
        if user.id:
            userid = user.id
        else:
            userid = -1

        data = {
            'house': house_info,
            'user_id': userid
        }
        return http.JsonResponse({'data': data, "errmsg": "OK", "errno": 0})
